<?php

/**
 * @version			$Id$
 * @create 			2015-10-21 22:10:09 By xjiujiu
 * @description     HongJuZi Framework
 * @copyRight 		Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
defined('_HEXEC') or die('Restricted access!');

//导入引用文件
HClass::import('config.popo.wxmenupopo, app.admin.action.AdminAction, model.wxmenumodel');
HClass::import('vendor.sdk.weixin.wechatmenuhelper');

/**
 * 微信菜单的动作类 
 * 
 * 主要处理后台管理主页的相关请求动作 
 * 
 * @author 			xjiujiu <xjiujiu@foxmail.com>
 * @package 		app.admin.action
 * @since 			1.0.0
 */
class WxmenuAction extends AdminAction
{

    /**
     * 构造函数 
     * 
     * 初始化类变量 
     * 
     * @access public
     */
    public function __construct() 
    {
        parent::__construct();
        $this->_popo        = new WxmenuPopo();
        $this->_model       = new WxmenuModel($this->_popo);
    }

    /**
     * 主页动作 
     * 
     * @access public
     */
    public function index()
    {        
        $this->_search();

        $this->_render('wxmenu/list');
    }

    protected function _otherJobsAfterAddView()
    {
        parent::_otherJobsAfterAddView();
        $this->_assignTypeList();
    }

    protected function _otherJobsAfterEditView()
    {
        parent::_otherJobsAfterEditView();
        $this->_assignTypeList();
    }

    protected function _otherJobsAfterList()
    {
        parent::_otherJobsAfterList();
        $this->_assignTypeMap();
    }

    private function _assignTypeMap()
    {
        $list   = HResponse::getAttribute('list');
        if(!$list) {
            return;
        }
        $catList    = $this->_category->getAllRowsByFields(
            '`id`, `name`',
            HSqlHelper::whereInByListMap('id', 'type', $list)
        );
        HResponse::registerFormatMap('type', 'name', HArray::turnItemValueAsKey($catList, 'id'));
    }

    private function _assignTypeList()
    {
        HResponse::setAttribute('type_list', $this->_category->getSubCategoryByIdentifier('cat-wx-menu', false));
    }

    /**
     * 微信菜单添加
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function awxadd()
    {
        HVerify::isAjax();
        $this->_addWXMenu();
        HResponse::json(array('rs' => true, 'message' => '添加微信菜单成功！'));
    }

    /**
     * 添加微信菜单
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    private function _addWXMenu()
    {
        $buttonList     = $this->_model->getAllRowsByFields(
            '`id`, `name`, `type`, `key`, `url`',
            '`parent_id` < 1'
        );
        if(!$buttonList) {
            throw new HVerifyException('菜单为空，请先添加可用菜单！');
        }
        $catList    = $this->_category->getSubCategoryByIdentifier('cat-wx-menu', false);
        $catMap     = HArray::turnItemValueAsKey($catList, 'id');
        $data       = array();
        foreach($buttonList as $btn) {
            $subList    = $this->_model->getAllRowsByFields(
                '`name`, `type`, `key`, `url`',
                '`parent_id` = ' . $btn['id']
            );
            $menu   = array();
            foreach($subList as &$item) {
                $item['type']   = $catMap[$item['type']]['identifier'];
                $item['key']    = !$item['key'] ? '' : $item['key'];
                if('view' == $item['type']) {
                    $item['url']    = HResponse::url($item['url']);
                }
            }
            if(!$subList) {
                $ele            = array(
                    'name' => $btn['name'],
                    'type' => $catMap[$btn['type']]['identifier'],
                    'key' => !$btn['key'] ? '' : $btn['key']
                );
                if('view' == $ele['type']) {
                    $ele['url']     = HResponse::url($btn['url']);
                }
                $data['button'][]   = $ele;
            } else {
                $data['button'][]   = array(
                    'name' => $btn['name'],
                    'sub_button' => $subList
                );
            }
        }
        $menuJson       = json_encode($data, JSON_UNESCAPED_UNICODE);
        $wxCfg          = $this->_getWechatCfg(HRequest::getParameter('shop_id'));
        $wechatMenu     = new WechatMenuHelper($wxCfg['app_id'], $wxCfg['app_secret']);
        $wechatMenu->requestAccessToken($wxCfg['shop_id'])->create($menuJson);
    }

    /**
     * 删除微信菜单
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function awxdel()
    {
        HVerify::isAjax();
        $this->_wxDel();
        HResponse::json(array('rs' => true, 'message' => '删除成功！'));
    }

    /**
     * 删除微信菜单
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    private function _wxDel()
    {
        $wxCfg          = $this->_getWechatCfg(HRequest::getParameter('shop_id'));
        $wechatMenu     = new WechatMenuHelper($wxCfg['app_id'], $wxCfg['app_secret']);
        $wechatMenu->requestAccessToken($wxCfg['shop_id'])->delete();
    }

    /**
     * 菜单查询
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function awxquery()
    {
        HVerify::isAjax();
        $wxCfg          = $this->_getWechatCfg(HRequest::getParameter('shop_id'));
        $wechatMenu     = new WechatMenuHelper($wxCfg['app_id'], $wxCfg['app_secret']);
        $json           = $wechatMenu->requestAccessToken($wxCfg['shop_id'])->query();
        if(0 < $json['errcode']) {
            throw new HVerifyException('查询失败！' . $json['errcode'] . ':' . $json['errmsg']);
        }
        HResponse::json(array('rs' => true, 'message' => '查询结果：' . var_export($json, true)));
    }

    /**
     * 重生成菜单
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function awxrebuild()
    {
        HVerify::isAjax();
        $this->_wxDel();
        $this->_addWXMenu();
        HResponse::json(array('rs' => true, 'message' => '重新生成微信菜单成功！'));
    }

}

?>
